package org.rcgwt.client.ui.fields;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.datepicker.client.DatePicker;

public class DateChooser extends Composite {
	private TextBox dateField;
	private PushButton dateButton;
	private DatePicker datePicker;
	private PopupPanel popup;
	private DateTimeFormat dateFormat = DateTimeFormat.getShortDateFormat();
	private boolean isPopupOpened = false;
	
	public DateChooser() {
		// Load resources
		Resources resources = GWT.<Resources> create(Resources.class);
		
		// Table to align the text field and button
		FlexTable table = new FlexTable();
		table.setCellSpacing(4);

		// Date input field
		dateField = new TextBox();
		table.setWidget(0, 0, dateField);
		dateField.addBlurHandler(new BlurHandler() {
			
			@Override
			public void onBlur(BlurEvent event) {
				// Change date picker value.
				Date dt = dateFormat.parse(dateField.getText());
				datePicker.setValue(dt);
			}
		});

		// Date chooser button
		dateButton = new PushButton(new Image(resources.dateChooserButton()));
		table.setWidget(0, 1, dateButton);
		dateButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				isPopupOpened = true;
				popup.showRelativeTo(DateChooser.this.dateButton);
			}
		});

		// Calendar popup
		popup = new PopupPanel(true);
		datePicker = new DatePicker();
		popup.setWidget(datePicker);
		datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
			
			@Override
			public void onValueChange(ValueChangeEvent<Date> event) {
				if (isPopupOpened) {
					// Hide the date picker
					isPopupOpened = false;
					popup.hide();
					
					// Set date in the text field
					Date dt = event.getValue();
					dateField.setText(dateFormat.format(dt));
				}
			}
		});
		initWidget(table);
	}

	  /**
	   * The default resources used by this widget.
	   */
	  public interface Resources extends ClientBundle {
	    /**
	     * An image representing the drag thumb.
	     */
	    @Source("dateChooser.gif")
	    ImageResource dateChooserButton();
	  }
}
